package com.Policing.Polling;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Adapter.MyBaseExpandableListAdapter;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.Okhttps.HttpOkHttp;
import com.Policing.R;
import com.Policing.Since_case.Since_case;
import com.Policing.menu.Group;
import com.Policing.menu.Item;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Polling_Scheme extends BaseActivity implements OnDismissListener {
    private ImageView fh;
    private TextView title_text;
    private Button warn_add,normal;
    private String taskPointContentId="",pointContentId="";
    private ExpandableListView exlist_lol;
    private ArrayList<Group> gData = null;
    private List<String> errorId = new ArrayList<>();
    private ArrayList<ArrayList<Item>> iData = null;
    private ArrayList<Item> lData = null;
    private String url="http://"+ Ip_Set.IP+"/api/pointContentExceptionQuery";
    private String taskPointContentExceptionSolved="http://"+ Ip_Set.IP+"/api/taskPointContentExceptionSolved";
    private Context mContext;
    private MyBaseExpandableListAdapter myAdapter = null;
    @Override
    public int intiLayout() {
        return R.layout.maintain_scheme;
    }

    @Override
    public void initView() {
        mContext = this;
        normal = (Button) findViewById(R.id.normal);
        taskPointContentId = getIntent().getStringExtra("taskPointContentId");
        pointContentId= getIntent().getStringExtra("pointContentId");
        exlist_lol = (ExpandableListView) findViewById(R.id.exlist_lol);
        fh = (ImageView) findViewById(R.id.fh);
        title_text = (TextView) findViewById(R.id.title_text);
        warn_add = (Button) findViewById(R.id.warn_add);

    }

    @Override
    public void initData() {
        title_text.setText("异常库");
        load();
        fh.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("id",getIntent().getStringExtra("id"));
            setResult(3,intent);
            finish();
        });
        //为列表设置点击事件
        exlist_lol.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {

            new AlertView(" 提示！", "异常是否已解决！", "取消",new String[]{"确定"}, null, mContext, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    //取消：position=-1,确定 position=0
                    if (position==0){
                        if (Since_case.set().getONorOff()) {
                            taskPointContentExceptionSolved(iData.get(groupPosition).get(childPosition).getId(), taskPointContentId);
                        }else {
                            Intent intent = new Intent();
                            intent.putExtra("id",getIntent().getStringExtra("id"));
                            setResult(3,intent);
                            finish();

                        }
                    }
                    if (position==-1){

                    }

                }
            }).setCancelable(true).setOnDismissListener(Polling_Scheme.this).show();
            // finish();
            // Toast.makeText(mContext, "你点击了：" + iData.get(groupPosition).get(childPosition).getiName(), Toast.LENGTH_SHORT).show();
            return true;
        });
        warn_add.setOnClickListener(v -> {
            Intent intent = new Intent(Polling_Scheme.this,CanniBalize_cheme.class);
            intent.putExtra("taskPointContentId",taskPointContentId);
            startActivityForResult(intent,8);
        });
        normal.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.putExtra("id",getIntent().getStringExtra("id"));
            Polling_Scheme.this.setResult(1,intent);
            Polling_Scheme.this.finish();//把item的内容返回给之前的activity
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==8&&resultCode==8){
            Intent intent = new Intent();
            intent.putExtra("id",getIntent().getStringExtra("id"));
            //返回值8为提交异常后返回
            Polling_Scheme.this.setResult(8,intent);
            Polling_Scheme.this.finish();//把item的内容返回给之前的activity
        }
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                Toast.makeText(Polling_Scheme.this,"再按一次返回",Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                Intent intent = new Intent();
                intent.putExtra("id",getIntent().getStringExtra("id"));
                setResult(3,intent);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void load(){
        if (Since_case.set().getONorOff()) {
            new Thread(() -> {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("pointContentId", pointContentId)
                        .add("source", Since_case.set().getSource()); //传递键值对参数
                final Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //数据准备
                        gData = new ArrayList<Group>();
                        iData = new ArrayList<ArrayList<Item>>();
                        final String responseData = response.body().string();
                        Gson gson = new Gson();
                        java.lang.reflect.Type type = new TypeToken<Scheme_bean>() {
                        }.getType();
                        final Scheme_bean jsonBean = gson.fromJson(responseData, type);
                        if (jsonBean.getState().equals("1")) {
                            for (int i = 0; i < jsonBean.getExceptions().size(); i++) {
                                gData.add(new Group(jsonBean.getExceptions().get(i).getExceptionText()));
                                lData = new ArrayList<Item>();
                                for (int j = 0; j < jsonBean.getExceptions().get(i).getExceptionSolves().size(); j++) {

                                    lData.add(new Item(jsonBean.getExceptions().get(i).getExceptionSolves().get(j).getText(), jsonBean.getExceptions().get(i).getExceptionSolves().get(j).getSolveId()));

                                    Log.i("123123", iData.toString());
                                }
                                iData.add(lData);
                            }
                            runOnUiThread(() -> {
                                myAdapter = new MyBaseExpandableListAdapter(gData, iData, mContext);
                                exlist_lol.setAdapter(myAdapter);
                            });

                        }
                        Log.i("321123", responseData);
                    }
                });
            }).start();
        } else {
            gData = new ArrayList<Group>();
            iData = new ArrayList<ArrayList<Item>>();
            int position = Since_case.set().getPointContentIdList().indexOf(pointContentId);
            if (position != -1) {
                try {
                    final Scheme_bean jsonBean = Since_case.set().getSchemeBeanList().get(position);
                    if (jsonBean.getState().equals("1")) {
                        for (int i = 0; i < jsonBean.getExceptions().size(); i++) {
                            gData.add(new Group(jsonBean.getExceptions().get(i).getExceptionText()));
                            lData = new ArrayList<Item>();
                            for (int j = 0; j < jsonBean.getExceptions().get(i).getExceptionSolves().size(); j++) {
                                lData.add(new Item(jsonBean.getExceptions().get(i).getExceptionSolves().get(j).getText(), jsonBean.getExceptions().get(i).getExceptionSolves().get(j).getSolveId()));
                                Log.i("123123", iData.toString());
                            }
                            iData.add(lData);
                        }
                        runOnUiThread(() -> {
                            myAdapter = new MyBaseExpandableListAdapter(gData, iData, mContext);
                            exlist_lol.setAdapter(myAdapter);
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("异常数据", "Polling_Scheme");
                }
            }

        }
    }
    @Override
    public void onDismiss(Object o) {

    }
    private  void taskPointContentExceptionSolved(String solveId,String taskPointContentId){
        Map<String,String> map = new HashMap<>();
        map.put("solveId",solveId);
        map.put("taskPointContentId",taskPointContentId);
        map.put("source",Since_case.set().getSource());
        HttpOkHttp.getInstance().requestPost(taskPointContentExceptionSolved, map, new HttpOkHttp.OkHttpCallBack<String>() {
            @Override
            public void requestSuccess(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getString("state").equals("1")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                toastShort("提交成功！");
                                finish();
                            }
                        });
                    }
                    if (jsonObject.getString("state").equals("2")){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                toastShort("提交失败！");
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(String message) {

            }
        },String.class);
    }
}
